//
//  DLChooseAddressView.m
//  SimpleShop
//
//  Created by 陈俭红 on 2021/11/27.
//  Copyright © 2021 神廷. All rights reserved.
//

#import "DLAddressPickerView.h"

typedef void(^ChooseBlock)(NSArray * addressArray);

@interface DLAddressPickerView () <UIPickerViewDataSource, UIPickerViewDelegate>
/**  */
@property (nonatomic, strong) UIView * bgView;
/**  */
@property (nonatomic, strong) UIButton * cancelBtn;
/**  */
@property (nonatomic, strong) UIButton * sureBtn;
/**  */
@property (nonatomic, strong) UIPickerView * pickerView;
/** 数组 */
@property (nonatomic, strong) NSMutableArray<NSArray *> * dataArray;
/** 数组 */
@property (nonatomic, strong) NSMutableArray<DLAddressModel *> * selArray;
/**  */
@property (nonatomic, copy) ChooseBlock chooseBlock;
/**  */
@property (nonatomic, assign) NSInteger maxCom;
@end

@implementation DLAddressPickerView

//MARK: Cycle Methods
+ (DLAddressPickerView *)showAddressPickerViewWithMaxCom:(NSInteger)maxCom block:(void(^)(NSArray * addressArray))block{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    DLAddressPickerView * view = [[DLAddressPickerView alloc] initWithFrame:window.bounds];
    view.chooseBlock = block;
    view.maxCom = maxCom;
    [window addSubview:view];
    return view;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addAllViews];
        [self showPicView];
        [self loadRegionDataWithParentCode:@"1" com:0];
    }
    return self;
}

//MARK: Custom Methods
- (void)addAllViews{
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self addSubview:self.bgView];
    [self.bgView addSubview:self.cancelBtn];
    [self.bgView addSubview:self.sureBtn];
    [self.bgView addSubview:self.pickerView];
}

- (void)showPicView{
    [UIView animateWithDuration:0.3 animations:^{
        self.bgView.frame = CGRectMake(0, self.height - (250 + kBottomSafeHeight), self.width, 250 + kBottomSafeHeight);
    }];
}

- (void)hiddenPicView{
    [UIView animateWithDuration:0.3 animations:^{
        self.bgView.frame = CGRectMake(0, self.height, self.width, 250 + kBottomSafeHeight);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - http methods
- (void)loadRegionDataWithParentCode:(NSString *)parentCode com:(NSInteger)com{
    NSDictionary * params = @{@"parentCode":parentCode};
    [HNSH_ShopNetServer requestRegionListWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray * array = [NSArray yy_modelArrayWithClass:DLAddressModel.class json:responseObject.resultset];
            [self.dataArray replaceObjectAtIndex:com withObject:array];
            if (com == 0) {
                [self pickerView:self.pickerView didSelectRow:0 inComponent:0];
                [self.pickerView reloadAllComponents];
            } else {
                [self.pickerView reloadComponent:com];
                [self.pickerView selectRow:0 inComponent:com animated:YES];
                [self pickerView:self.pickerView didSelectRow:0 inComponent:com];
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark - events response
- (void)selectAddressComplete{
    if (self.chooseBlock) {
        self.chooseBlock(self.selArray.copy);
    }
    [self hiddenPicView];
}

- (void)selectAddressClose{
    [self hiddenPicView];
}

#pragma mark - UIPickerViewDataSource
//确定picker的轮子个数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return self.dataArray.count;
}

//确定picker的每个轮子的item数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.dataArray[component].count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 36;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel * label = (UILabel *)view;
    if (label == nil) {
        label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor blackColor];
        [label setTextAlignment:0];
        [label setBackgroundColor:[UIColor clearColor]];
        [label setTextAlignment:NSTextAlignmentCenter];
    }
    DLAddressModel * area = self.dataArray[component][row];
    label.text = area.name;
    return label;
}

//确定每个轮子的每一项显示什么内容
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSDictionary * attrDic = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontOfSize:12]};
    DLAddressModel * area = self.dataArray[component][row];
    NSAttributedString * attrString = [[NSAttributedString alloc] initWithString:area.name attributes:attrDic];
    return attrString;
}

//监听轮子的移动
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    DLAddressModel * model = self.dataArray[component][row];
    [self.selArray replaceObjectAtIndex:component withObject:model];
    if (component != self.dataArray.count - 1) {
        [self loadRegionDataWithParentCode:model.code com:component + 1];
    }
}

//MARK: Setter Methods
- (void)setMaxCom:(NSInteger)maxCom{
    _maxCom = maxCom;
    
    [self.dataArray removeAllObjects];
    [self.selArray removeAllObjects];
    for (int i = 0; i < maxCom; i++) {
        [self.dataArray addObject:@[]];
        [self.selArray addObject:[DLAddressModel new]];
    }
}

//MARK: Getter Methods
- (NSMutableArray <NSArray *> *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray <DLAddressModel *> *)selArray{
    if (!_selArray) {
        _selArray = [NSMutableArray array];
    }
    return _selArray;
}

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [UIView new];
        _bgView.frame = CGRectMake(0, self.height, self.width, 250 + kBottomSafeHeight);
        _bgView.backgroundColor = [UIColor appWhiteLabelColor];
    }
    return _bgView;
}

- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton new];
        _cancelBtn.frame = CGRectMake(0, 0, 70, 50);
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor appGreenColor] forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelBtn addTarget:self action:@selector(selectAddressClose) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

- (UIButton *)sureBtn{
    if (!_sureBtn) {
        _sureBtn = [UIButton new];
        _sureBtn.frame = CGRectMake(self.bgView.width - 70, 0, 70, 50);
        [_sureBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor appGreenColor] forState:UIControlStateNormal];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_sureBtn addTarget:self action:@selector(selectAddressComplete) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

- (UIPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [UIPickerView new];
        _pickerView.frame = CGRectMake(0, 50, self.bgView.width, self.bgView.height - 50 - kBottomSafeHeight);
        _pickerView.delegate   = self;
        _pickerView.dataSource = self;
    }
    return _pickerView;
}
@end
